class Dep {
  constructor() {
    this.subscribers = new Set(); // 存放收集的依赖，即副作用函数
  }

  depend() {
    if (activeEffect) {
      this.subscribers.add(activeEffect);
    }
  }

  notify() {
    this.subscribers.forEach((effect) => effect());
  }
}

const dep = new Dep();
let activeEffect = null;
function watchEffect(effect) {
  activeEffect = effect;
  dep.depend(); // 自动收集依赖
  effect(); // 收集完依赖后执行该依赖函数
  activeEffect = null;
}

const info = { counter: 100, name: "why" };
console.log("==自动收集依赖==");
watchEffect(() => {
  console.log(info.counter * 2);
});
watchEffect(() => {
  console.log(info.counter * info.counter);
});
watchEffect(() => {
  console.log(info.name);
});
console.log("=====更新=====");
info.counter++;
dep.notify();
// 更新时，info.name的副作用函数每次都被被执行
